<?php
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
require 'db.php'; // 引入数据库连接
include_once 'secret/jwt.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;


// 检查是否存在 token
if (!isset($_COOKIE['token'])) {
    echo '用户未登录';
    header('Refresh: 3; URL=login_form.html');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    // 解码 JWT token
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $role = $decoded->data->role;
    $user_id = $decoded->data->id;

    // 检查是否为 POST 请求
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $title = $_POST['title'];
        $content = $_POST['content'];

        // 默认文章状态为待审核
        $status = 'pending';

        // 插入文章到数据库
        $stmt = $conn->prepare("INSERT INTO articles (title, content, author, status,author_name) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("ssiss", $title, $content, $user_id, $status, $username);

        if ($stmt->execute()) {
            echo '文章发布成功,等待管理员审核';
            header("refresh:3;url=profile.html");
        } else {
            echo json_encode(['status' => 'error', 'message' => '发布文章时出错: ' . $conn->error]);
        }

        $stmt->close();
        $conn->close();
    } else {
        echo json_encode(['status' => 'error', 'message' => '无效的请求方法']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => '访问被拒绝: ' . $e->getMessage()]);
}
?>

